import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class BillManagementDialog extends JDialog {
    public BillManagementDialog(JFrame owner) {
        super(owner, "账单管理", true);
        setSize(400, 300); // 增加对话框的大小
        setLocationRelativeTo(owner); // 居中显示
        setLayout(new BorderLayout()); // 使用 BorderLayout

        // 创建一个面板用于放置按钮，使用 FlowLayout 并设置边距
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 30, 30)); // 左右间距为30像素，上下间距为30像素
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); // 设置面板边框以增加额外的边距

        // 创建按钮
        JButton incomeButton = new JButton("1. 收入账单管理");
        incomeButton.setPreferredSize(new Dimension(300, 70)); // 设置按钮宽度为300像素，高度为70像素
        incomeButton.addActionListener(e -> {
            new IncomeBillManagementDialog(owner).setVisible(true);
            dispose(); // 关闭当前对话框
        });

        JButton expenseButton = new JButton("2. 支出账单管理");
        expenseButton.setPreferredSize(new Dimension(300, 70)); // 设置按钮宽度为300像素，高度为70像素
        expenseButton.addActionListener(e -> {
            new ExpenseBillManagementDialog(owner).setVisible(true);
            dispose(); // 关闭当前对话框
        });

        // 添加按钮到按钮面板
        buttonPanel.add(incomeButton);
        buttonPanel.add(expenseButton);

        // 将按钮面板添加到对话框中心
        add(buttonPanel, BorderLayout.CENTER);

        // 添加键盘监听器
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_1 || e.getKeyCode() == KeyEvent.VK_NUMPAD1) {
                    incomeButton.doClick(); // 模拟点击收入账单管理按钮
                } else if (e.getKeyCode() == KeyEvent.VK_2 || e.getKeyCode() == KeyEvent.VK_NUMPAD2) {
                    expenseButton.doClick(); // 模拟点击支出账单管理按钮
                }
            }
        });

        // 使对话框获得焦点，以便可以接收键盘事件
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowOpened(WindowEvent e) {
                requestFocusInWindow();
            }
        });
    }
}

class IncomeBillManagementDialog extends JDialog {
    private JTable table;
    private DefaultTableModel model;
    private JTextField dateField;
    private JTextField categoryField;
    private JTextField startDateField;
    private JTextField endDateField;
    private JButton filterButton;
    private JButton backButton;

    public IncomeBillManagementDialog(JFrame owner) {
        super(owner, "收入账单管理", true);
        initializeComponents(owner);
    }

    private void initializeComponents(JFrame owner) {
        setSize(800, 400);
        setLocationRelativeTo(owner); // 居中显示
        setLayout(new BorderLayout());

        // 创建表格模型
        model = new DefaultTableModel();
        model.setColumnIdentifiers(new String[]{"日期", "金额", "类别", "备注"});

        // 创建表格
        table = new JTable(model) {
            @Override
            public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
                Component c = super.prepareRenderer(renderer, row, column);
                ((JLabel) c).setHorizontalAlignment(SwingConstants.CENTER);
                return c;
            }
        };
        JScrollPane scrollPane = new JScrollPane(table);

        // 创建筛选输入字段
        JPanel filterPanel = new JPanel(new FlowLayout());
        filterPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); // 增加边距
        dateField = new JTextField(10);
        categoryField = new JTextField(10);
        startDateField = new JTextField(10);
        endDateField = new JTextField(10);
        filterButton = new JButton("筛选");
        backButton = new JButton("返回");

        // 默认隐藏返回按钮
        backButton.setVisible(false);

        filterPanel.add(new JLabel("日期:"));
        filterPanel.add(dateField);
        filterPanel.add(new JLabel("类别:"));
        filterPanel.add(categoryField);
        filterPanel.add(new JLabel("开始日期:"));
        filterPanel.add(startDateField);
        filterPanel.add(new JLabel("结束日期:"));
        filterPanel.add(endDateField);
        filterPanel.add(filterButton);
        filterPanel.add(backButton);

        // 添加筛选按钮的监听器
        filterButton.addActionListener(e -> filterBills());

        // 添加返回按钮的监听器
        backButton.addActionListener(e -> {
            clearTableAndFields(); // 清空表格和搜索字段
            loadBills(); // 重新加载所有账单
            backButton.setVisible(false); // 隐藏返回按钮
            backToMainMenu(owner); // 返回主菜单
        });

        // 添加组件到对话框
        add(scrollPane, BorderLayout.CENTER);
        add(filterPanel, BorderLayout.SOUTH); // 放置在底部

        // 加载所有收入账单
        loadBills();
    }

    private void loadBills() {
        String filePath = "Gitzuoye/src/income";
        List<String[]> bills = readBillsFromFile(filePath);
        for (String[] bill : bills) {
            model.addRow(bill);
        }
    }

    private List<String[]> readBillsFromFile(String filePath) {
        List<String[]> bills = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                bills.add(line.split(","));
            }
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, "无法读取账单文件，请检查文件路径或权限。", "错误", JOptionPane.ERROR_MESSAGE);
        }
        return bills;
    }

    private void filterBills() {
        String date = dateField.getText().trim();
        String category = categoryField.getText().trim();
        String startDate = startDateField.getText().trim();
        String endDate = endDateField.getText().trim();

        // 清除表格内容
        model.setRowCount(0);

        // 重新加载符合条件的账单
        String filePath = "Gitzuoye/src/income";
        List<String[]> bills = readBillsFromFile(filePath);
        for (String[] bill : bills) {
            if (matchesCriteria(bill, date, category, startDate, endDate)) {
                model.addRow(bill);
            }
        }

        // 显示返回按钮
        backButton.setVisible(true);
    }

    private boolean matchesCriteria(String[] bill, String date, String category, String startDate, String endDate) {
        boolean dateMatch = date.isEmpty() || bill[0].equals(date);
        boolean categoryMatch = category.isEmpty() || bill[2].equals(category);
        boolean startDateMatch = startDate.isEmpty() || bill[0].compareTo(startDate) >= 0;
        boolean endDateMatch = endDate.isEmpty() || bill[0].compareTo(endDate) <= 0;

        return dateMatch && categoryMatch && startDateMatch && endDateMatch;
    }

    private void clearTableAndFields() {
        // 清空表格内容
        model.setRowCount(0);

        // 清空搜索字段
        dateField.setText("");
        categoryField.setText("");
        startDateField.setText("");
        endDateField.setText("");
    }

    private void backToMainMenu(JFrame owner) {
        new BillManagementDialog(owner).setVisible(true);
        dispose(); // 关闭当前对话框
    }
}

class ExpenseBillManagementDialog extends JDialog {
    private JTable table;
    private DefaultTableModel model;
    private JTextField dateField;
    private JTextField categoryField;
    private JTextField startDateField;
    private JTextField endDateField;
    private JButton filterButton;
    private JButton backButton;

    public ExpenseBillManagementDialog(JFrame owner) {
        super(owner, "支出账单管理", true);
        initializeComponents(owner);
    }

    private void initializeComponents(JFrame owner) {
        setSize(800, 400);
        setLocationRelativeTo(owner); // 居中显示
        setLayout(new BorderLayout());

        // 创建表格模型
        model = new DefaultTableModel();
        model.setColumnIdentifiers(new String[]{"日期", "金额", "类别", "备注"});

        // 创建表格
        table = new JTable(model) {
            @Override
            public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
                Component c = super.prepareRenderer(renderer, row, column);
                ((JLabel) c).setHorizontalAlignment(SwingConstants.CENTER);
                return c;
            }
        };
        JScrollPane scrollPane = new JScrollPane(table);

        // 创建筛选输入字段
        JPanel filterPanel = new JPanel(new FlowLayout());
        filterPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); // 增加边距
        dateField = new JTextField(10);
        categoryField = new JTextField(10);
        startDateField = new JTextField(10);
        endDateField = new JTextField(10);
        filterButton = new JButton("筛选");
        backButton = new JButton("返回");

        // 默认隐藏返回按钮
        backButton.setVisible(false);

        filterPanel.add(new JLabel("日期:"));
        filterPanel.add(dateField);
        filterPanel.add(new JLabel("类别:"));
        filterPanel.add(categoryField);
        filterPanel.add(new JLabel("开始日期:"));
        filterPanel.add(startDateField);
        filterPanel.add(new JLabel("结束日期:"));
        filterPanel.add(endDateField);
        filterPanel.add(filterButton);
        filterPanel.add(backButton);

        // 添加筛选按钮的监听器
        filterButton.addActionListener(e -> filterBills());

        // 添加返回按钮的监听器
        backButton.addActionListener(e -> {
            clearTableAndFields(); // 清空表格和搜索字段
            loadBills(); // 重新加载所有账单
            backButton.setVisible(false); // 隐藏返回按钮
            backToMainMenu(owner); // 返回主菜单
        });

        // 添加组件到对话框
        add(scrollPane, BorderLayout.CENTER);
        add(filterPanel, BorderLayout.SOUTH); // 放置在底部

        // 加载所有支出账单
        loadBills();
    }

    private void loadBills() {
        String filePath = "Gitzuoye/src/expenses";
        List<String[]> bills = readBillsFromFile(filePath);
        for (String[] bill : bills) {
            model.addRow(bill);
        }
    }

    private List<String[]> readBillsFromFile(String filePath) {
        List<String[]> bills = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                bills.add(line.split(","));
            }
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, "无法读取账单文件，请检查文件路径或权限。", "错误", JOptionPane.ERROR_MESSAGE);
        }
        return bills;
    }

    private void filterBills() {
        String date = dateField.getText().trim();
        String category = categoryField.getText().trim();
        String startDate = startDateField.getText().trim();
        String endDate = endDateField.getText().trim();

        // 清除表格内容
        model.setRowCount(0);

        // 重新加载符合条件的账单
        String filePath = "Gitzuoye/src/expenses";
        List<String[]> bills = readBillsFromFile(filePath);
        for (String[] bill : bills) {
            if (matchesCriteria(bill, date, category, startDate, endDate)) {
                model.addRow(bill);
            }
        }

        // 显示返回按钮
        backButton.setVisible(true);
    }

    private boolean matchesCriteria(String[] bill, String date, String category, String startDate, String endDate) {
        boolean dateMatch = date.isEmpty() || bill[0].equals(date);
        boolean categoryMatch = category.isEmpty() || bill[2].equals(category);
        boolean startDateMatch = startDate.isEmpty() || bill[0].compareTo(startDate) >= 0;
        boolean endDateMatch = endDate.isEmpty() || bill[0].compareTo(endDate) <= 0;

        return dateMatch && categoryMatch && startDateMatch && endDateMatch;
    }

    private void clearTableAndFields() {
        // 清空表格内容
        model.setRowCount(0);

        // 清空搜索字段
        dateField.setText("");
        categoryField.setText("");
        startDateField.setText("");
        endDateField.setText("");
    }

    private void backToMainMenu(JFrame owner) {
        new BillManagementDialog(owner).setVisible(true);
        dispose(); // 关闭当前对话框
    }
}